package weifei.live.simulation.controller;


import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import jakarta.servlet.http.HttpServletRequest;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
import weifei.live.simulation.entity.ChatGroup;
import weifei.live.simulation.entity.GroupMember;
import weifei.live.simulation.service.UserService;
import weifei.web.Result;


@RestController
@RequestMapping("/user")
public class GroupUserController
{
    @Autowired
    private UserService userService;


    @Autowired
    private ChatGroup dao_group;
    @Autowired
    private GroupMember dao_group_member;


    /** 此处有 登录拦截 */


    @PostMapping("/joinGroup")
    public Result joinGroup(HttpServletRequest request, @RequestParam("id") int groupId)
    {
        QueryWrapper<ChatGroup> qw_group = new QueryWrapper<>();
        qw_group.eq(ChatGroup.Column.ID.getName(), groupId);
        var target = this.dao_group.selectOne(qw_group);
        if (target == null)
            return Result.failed("群聊不存在");

        var token = request.getHeader("token");
        var user_id = this.userService.getUserIDByToken(token);

        QueryWrapper<GroupMember> qw_group_member = new QueryWrapper<>();
        qw_group_member.eq(GroupMember.Column.UserID.getName(), user_id);
        qw_group_member.eq(GroupMember.Column.GroupID.getName(), groupId);
        var member_data = this.dao_group_member.selectOne(qw_group_member);
        if (member_data != null)
            return Result.failed("你已经是该群成员");

        var m = new GroupMember(groupId, user_id);
        if (!m.insert())
            return Result.exception("加入失败，数据库出错");
        return Result.success("加入成功");
    }


    @PostMapping("/quitGroup")
    public Result quitGroup(HttpServletRequest request, @RequestParam("id") int groupId)
    {
        QueryWrapper<ChatGroup> qw_group = new QueryWrapper<>();
        qw_group.eq(ChatGroup.Column.ID.getName(), groupId);
        var target = new ChatGroup().selectOne(qw_group);
        if (target == null)
            return Result.failed("群聊不存在");

        var token = request.getHeader("token");
        var user_id = this.userService.getUserIDByToken(token);

        QueryWrapper<GroupMember> qw_group_member = new QueryWrapper<>();
        qw_group_member.eq(GroupMember.Column.UserID.getName(), user_id);
        qw_group_member.eq(GroupMember.Column.GroupID.getName(), groupId);
        var member_data = this.dao_group_member.selectOne(qw_group_member);
        if (member_data == null)
            return Result.failed("你不是该群成员");

        if (!member_data.deleteById())
            return Result.exception("退出失败，数据库出错");
        return Result.success("退出成功");
    }
}



